import { reqGetCode, reqUserRegister, reqUserLogin, reqUserInfo ,reqLogout} from "@/api"
import { setToken,getToken,removeToken } from "@/utils/token"
//登录与注册模块
const state = {
    code: '',
    token:getToken(),
    userInfo:{}
}
const mutations = {
    GETCODE(state, code) {
        state.code = code
    },
    USERLOGIN(state, token) {
        state.token = token
    },
    GETUSERINFO(state,userInfo){
        state.userInfo=userInfo
    },
    //清除本地数据
    CLEAR(state){
        state.token='';
        state.userInfo={}
        //本地存储清空
        removeToken()
    }
}
const actions = {
    //获取验证码
    async getCode({ commit }, phone) {
        let result = await reqGetCode(phone)
        // console.log(result)
        if (result.code == 200) {
            commit('GETCODE', result.data)
            return 'ok'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    //注册
    async userRegister({ commit }, user) {
        let result = await reqUserRegister(user)
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    //登录
    async userLogin({ commit }, user) {
        let result = await reqUserLogin(user)
        // console.log(result)
        //服务器下发token 用户唯一标识符
        //将来经常找服务器要token进行用户信息展示
        if (result.code == 200) {
            commit('USERLOGIN', result.data.token)
            //持久化储存token
            setToken(result.data.token)
            return 'ok'
        } else {
            return Promise.reject(new Error('fail'))
        }

    },
    //获取用户信息
    async getUserInfo({commit}) {
        let result = await reqUserInfo()
        // console.log(result)
        if (result.code == 200) {
            commit('GETUSERINFO', result.data)
            return 'ok'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    //清除用户信息
    async logout({commit}){
        let result=await reqLogout()
        if(result.code==200){
            commit('CLEAR')
            return 'ok'
        }else{
            return Promise.reject(new Error('fail'))
        }
    }
} 
const getters = {}
export default {
    state,
    mutations,
    actions,
    getters
}